import Banner from '../Banner/index';
import Mode from '../Mode/index';
import Action from '../Action/index';
import './home.less';
import { useEffect, useState, useRef } from 'react';
import { Popup, Picker, Dialog, Toast } from 'react-vant';
import {
  timeHourColumn,
  timeMinColumn,
  deviceId
} from '../../utils/staticData';
import {
  runningTextConvert,
  btnFitersText,
  modeToWorktime
} from '../../utils/filters';

export default function Home() {
  // 定时器变量
  const intervalId = useRef<NodeJS.Timeout | null>(null);
  /**
   * 当设备离线的时候，将 status设置为 2，待机状态
   */

  const [preTimeList, setPreTimeList] = useState<string[]>(['', '']);
  const [columns, setColumes] = useState([timeHourColumn(), timeMinColumn()]);

  const timeVisible: string = 'time';

  /**
   * 直接定义变量和使用useState钩子有以下区别：
   * 1. 直接定义变量： 直接在函数组件中定义变量时，它表现为普通的JavaScript变量。
   * 当变量发生变化时，不会触发组件的重新渲染，除非显式地重新渲染组件。
   * 2. useState钩子： useState是React中的内置钩子，允许函数组件管理状态。
   * 当你使用useState声明状态变量时，React会在状态变量更新时自动触发组件的重新渲染，从而确保组件反映更新后的状态值。
   */
  interface IState {
    mode: number; // 模式
    _mode: null | number; // 用来保存最后一次设置的模式，提前赋值
    runningState: number; // 运行状态: 0 = 待机 1=运行中 2=保温中 3=预约中
    switch: number; // 开始/取消: 0=取消 1=开始
    makeAnAppointment: number; // 预约时间
    RunTime: number; // 运行时间
    InsulationRunningTime: number; // 保温时间
    fault: number; // 0=无故障 1-5:有故障
    isOnline: boolean; // false=离线 true=在线
    _runTime: number;
  }
  const [visibleStr, setVisibleStr] = useState<String>('');
  const [btnTitle, setBtnTitle] = useState<String>('开始烹饪');
  const [deviceInfo, setDeviceInfo] = useState<IState>({
    mode: 0,
    _mode: null,
    runningState: 0,
    switch: 0,
    makeAnAppointment: 0,
    RunTime: 0,
    InsulationRunningTime: 0,
    fault: 0,
    isOnline: true,
    _runTime: 0 // 用来保存更该运行时间的值，每次点击开始/取消时，重置为 0
  });

  useEffect(() => {
    const quotient = Math.floor(deviceInfo.makeAnAppointment / 60);
    const remainder = deviceInfo.makeAnAppointment % 60;

    console.log('Quotient:', quotient);
    console.log('Remainder:', remainder);
    setPreTimeList([quotient.toString(), remainder.toString()]);
  }, [deviceInfo.makeAnAppointment]);

  // 根据status，设置按钮文字
  useEffect(() => {
    if (
      deviceInfo.runningState === 1 ||
      deviceInfo.runningState === 2 ||
      deviceInfo.runningState === 3
    ) {
      setBtnTitle('取消');
    }
  }, [deviceInfo.runningState]); // Specify the dependency array to listen for changes in yourVariable

  // 轮询快照接口
  useEffect(() => {
    // 这里是副作用的逻辑，类似于 componentDidMount
    intervalId.current = setInterval(() => {
      // 在这里执行你想要的操作
      getDeviceInfo();
    }, 1000);
    return () => {
      // 这里是清理副作用的逻辑，类似于 componentWillUnmount
      // 在组件卸载时清除定时器
      if (intervalId.current) {
        clearInterval(intervalId.current); // 清除定时器
      }
    };
  }, []); // 依赖数组为空，只在组件挂载和卸载时执行一次
  const Hejia = (window as any).Hejia;
  useEffect(() => {
    Hejia.ready(function () {
      // 页面加载完成后要立即调用Hejia全局对象执行的代码逻辑写这里
      getDeviceInfo();
    });
  }, []);

  // 解析获取到的设备信息数据
  const parseData = (params: any) => {
    params.forEach((e: any) => {
      let value = Number(e.value);

      const keys = [
        'switch',
        'makeAnAppointment',
        'RunTime',
        'InsulationRunningTime',
        'runningState',
        'fault'
      ];

      if (keys.includes(e.name)) {
        setDeviceInfo(pre => ({
          ...pre, // 使用对象展开符复制原对象的属性
          [e.name]: value // 更新特定属性的值
        }));
      }

      if (e.name === 'mode') {
        if (deviceInfo._mode == null || deviceInfo._mode == deviceInfo.mode) {
          setDeviceInfo(pre => ({
            ...pre,
            mode: value,
            _mode: value
          }));
        }
      }
    });
  };
  /**
   * 轮询事件
   */
  const getDeviceInfo = () => {
    // deviceId
    Hejia.getDeviceInfo(
      {},
      function (obj: any) {
        console.log(obj.device, '设备信息：：：');
        if (obj.device == undefined) return;

        /**
         * 第一级别：离线，设备离线级别最高，如果设备是离线状态，需要展示离线页面
         * 第二级别：故障
         */
        // 设备是否在线, 设置离线状态
        // 设备是否在线, 设置离线状态
        setDeviceInfo(pre => ({
          ...pre, // 使用对象展开符复制原对象的属性
          isOnline: obj.device.connected // 更新特定属性的值
        }));

        // 设备是否在线，设置故障状态
        if (obj.device.fault) {
          setDeviceInfo(pre => ({
            ...pre, // 使用对象展开符复制原对象的属性
            fault: obj.device.fault
          }));
        }

        parseData(obj.device.parameters);
      },
      function (msg: any, obj: any) {
        console.log(msg, '设备参数报错了---');
        console.log(obj.resultCode + obj.resultCodeMessage);
      }
    );
  };
  /**
   * @description 用于用户点击一个功能，点击需要停止轮询，成功后再继续困徐
   * @param {boolean} val true=>开启轮询 false=>关闭轮询
   */
  const handleLoopClick = (val: boolean) => {
    // true=>开启轮询 false=>关闭轮询
    if (val) {
      if (intervalId.current) {
        clearInterval(intervalId.current);
      }
      intervalId.current = setInterval(() => {
        // 在这里执行你想要的操作
        getDeviceInfo();
      }, 1000);
    } else {
      if (intervalId.current) {
        clearInterval(intervalId.current);
      }
    }
  };

  const handleModeChange = (val: number) => {
    console.log('handleModeChange:', val);

    if (val === 1 || val === 8) {
      setDeviceInfo(pre => ({
        ...pre,
        mode: val,
        RunTime: 0
      }));
    } else if (val === 9) {
      setDeviceInfo(pre => ({
        ...pre,
        mode: val,
        RunTime: 0,
        InsulationRunningTime: 720
      }));
    } else {
      setDeviceInfo(pre => ({
        ...pre,
        mode: val,
        RunTime: deviceInfo._runTime || modeToWorktime(val)
      }));
    }
  };
  const handleActionChange = (val: number) => {
    console.log('handleActionChange:', val);
    setDeviceInfo(pre => ({
      ...pre,
      RunTime: val,
      _runTime: val
    }));
  };

  const onClose = () => {
    setVisibleStr('');
    handleLoopClick(true);
  };
  const onOpen = () => {
    const quotient = Math.floor(deviceInfo.makeAnAppointment / 60);
    const remainder = deviceInfo.makeAnAppointment % 60;

    console.log('Quotient:', quotient);
    console.log('Remainder:', remainder);
    setPreTimeList([quotient.toString(), remainder.toString()]);
    handleLoopClick(false);
  };

  const onAppPop = () => setVisibleStr('time');
  const onCooker = () => {
    if (!deviceInfo.mode) {
      Toast.info('请先设置模式');
      return;
    }
    handleLoopClick(false);
    if (
      deviceInfo.runningState === 1 ||
      deviceInfo.runningState === 2 ||
      deviceInfo.runningState === 3
    ) {
      let msg = `设备${runningTextConvert(
        deviceInfo.runningState
      )}中，确定要取消${runningTextConvert(deviceInfo.runningState)}吗？`;
      if (deviceInfo.runningState === 1) {
        msg = `设备${runningTextConvert(
          deviceInfo.runningState
        )}中，确定要取消烹饪吗？`;
      }
      Dialog.confirm({
        message: msg,
        confirmButtonText: '确定',
        confirmButtonColor: 'var(--primary-color)',
        onCancel: () => {
          handleLoopClick(true);
        },
        onConfirm: () => {
          setDeviceInfo(pre => ({
            ...pre, // 使用对象展开符复制原对象的属性
            runningState: 0, // 更新特定属性的值
            makeAnAppointment: 0, // 更新特定属性的值
            mode: 0,
            _runTime: 0
          }));

          // 取消烹饪
          Hejia.setControlParam(
            {
              // deviceId,
              parameters: {
                param: [
                  {
                    name: 'switch',
                    content: 0
                  }
                ]
              }
            },
            function () {
              // success, no response
              setTimeout(() => {
                handleLoopClick(true);
              }, 2000);
              console.log('success');
            },
            function (msg: string, obj: any) {
              console.log(msg + obj.resultCode + obj.resultCodeMessage);
            }
          );
        }
      });
    } else {
      // 开始烹饪
      if (deviceInfo.makeAnAppointment) {
        setDeviceInfo(pre => ({
          ...pre, // 使用对象展开符复制原对象的属性
          runningState: 3, // 预约中
          _runTime: 0
        }));
      } else if (deviceInfo.mode === 9) {
        setDeviceInfo(pre => ({
          ...pre, // 使用对象展开符复制原对象的属性
          runningState: 2, // 保温中
          _runTime: 0
        }));
      } else {
        setDeviceInfo(pre => ({
          ...pre, // 使用对象展开符复制原对象的属性
          runningState: 1, // 运行中
          _runTime: 0
        }));
      }

      Hejia.setControlParam(
        {
          // deviceId,
          parameters: {
            param: [
              {
                name: 'switch',
                content: 1
              }
            ]
          }
        },
        function () {
          // success, no response
          setTimeout(() => {
            handleLoopClick(true);
          }, 2000);
          console.log('success');
        },
        function (msg: string, obj: any) {
          console.log(msg + obj.resultCode + obj.resultCodeMessage);
        }
      );
    }
  };

  const onAppCancel = () => {
    onClose();
    setDeviceInfo(pre => ({
      ...pre, // 使用对象展开符复制原对象的属性
      makeAnAppointment: 0 // 运行中
    }));
    Hejia.setControlParam(
      {
        // deviceId,
        parameters: {
          param: [
            {
              name: 'makeAnAppointment',
              content: 0
            }
          ]
        }
      },
      function () {
        // success, no response
        setTimeout(() => {
          handleLoopClick(true);
        }, 1000);
        console.log('success');
      },
      function (msg: string, obj: any) {
        console.log(msg + obj.resultCode + obj.resultCodeMessage);
      }
    );
  };

  return (
    <div className="home">
      <div>
        <Banner
          propsBanner={{
            status: deviceInfo.runningState,
            fault: deviceInfo.fault,
            isOnline: deviceInfo.isOnline,
            preTime: deviceInfo.makeAnAppointment,
            setWorkTime: deviceInfo.RunTime,
            warmDuration: deviceInfo.InsulationRunningTime
          }}
        />
        <Mode
          props={{
            mode: deviceInfo.mode,
            isOnline: deviceInfo.isOnline,
            status: deviceInfo.runningState
          }}
          onModeChange={handleModeChange}
          onLoopClick={handleLoopClick}
        />

        <Action
          propsAction={{
            RunTime: deviceInfo.RunTime,
            isOnline: deviceInfo.isOnline,
            status: deviceInfo.runningState,
            warmDuration: deviceInfo.InsulationRunningTime,
            mode: deviceInfo.mode
          }}
          onActionChange={handleActionChange}
          onLoopClick={handleLoopClick}
        />
        <div className="home-mask-wapper">
          {(!deviceInfo.isOnline ||
            (deviceInfo.runningState === 0 && deviceInfo.mode === 0)) && (
            <div className="mask"></div>
          )}
          <div className="footer">
            {deviceInfo.runningState == 0 && deviceInfo.mode != 9 && (
              <div className="appointment-btn" onClick={onAppPop}>
                {deviceInfo.makeAnAppointment ? '编辑预约' : '开始预约'}
              </div>
            )}
            <div className="stop-btn" onClick={onCooker}>
              {btnFitersText(
                deviceInfo.runningState,
                deviceInfo.makeAnAppointment,
                deviceInfo.mode
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 预约时间弹框 */}
      <Popup
        round
        visible={timeVisible === visibleStr}
        position="bottom"
        onOpen={onOpen}
        onClose={onClose}
      >
        <div className="app-wrapper">
          <Picker
            value={preTimeList}
            title="预约"
            placeholder=""
            columns={columns}
            onCancel={() => {
              onClose();
            }}
            onChange={(val: any) => {
              console.log(val, 'val==');

              if (val[0] == 24) {
                setColumes([timeHourColumn(), [{ text: '0', value: '0' }]]);
              } else {
                setColumes([timeHourColumn(), timeMinColumn()]);
              }
            }}
            onConfirm={(val: any) => {
              const mins: number = Number(val[0]) * 60 + Number(val[1]);
              console.log(mins, 'mins');
              onClose();
              setDeviceInfo(pre => ({
                ...pre, // 使用对象展开符复制原对象的属性
                makeAnAppointment: mins // 运行中
              }));

              Hejia.setControlParam(
                {
                  // deviceId,
                  parameters: {
                    param: [
                      {
                        name: 'makeAnAppointment',
                        content: mins
                      }
                    ]
                  }
                },
                function () {
                  // success, no response
                  console.log('success');
                },
                function (msg: string, obj: any) {
                  console.log(msg + obj.resultCode + obj.resultCodeMessage);
                }
              );
            }}
          />
          <div className="unit unit-hour">小时</div>
          <div className="unit unit-min">分钟</div>
        </div>
        {!!deviceInfo.makeAnAppointment && (
          <div className="btn-cancel" onClick={onAppCancel}>
            取消预约
          </div>
        )}
      </Popup>
    </div>
  );
}
